package com.pyp.kuaishou.controller;

import com.pyp.kuaishou.service.KSAuthService;
import com.pyp.kuaishou.service.KSPublishService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 作者: lauJinyu
 * REST API控制器：提供JSON格式的API接口
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class ApiController {

    private final KSAuthService ksAuthService;
    private final KSPublishService ksPublishService;

    /**
     * 获取访问令牌接口
     * @param request 包含appId的请求体
     * @return 访问令牌信息
     */
    @PostMapping("/auth/token")
    public ResponseEntity<Map<String, Object>> getToken(@RequestBody Map<String, String> request) {
        String appId = request.get("appId");
        log.info("收到获取token请求，appId: {}", appId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "此接口已废弃。请通过浏览器发起授权并等待快手回调 /kuaishou/auto-publish 或 /kuaishou/callback 以实时获取token");
        result.put("authorize_url", ksAuthService.buildAuthorizeUrl(appId));
        return ResponseEntity.ok(result);
    }

    /**
     * 发布视频接口
     * @param request 包含appId、storeId和其他参数的请求体
     * @return 发布结果
     */
    @PostMapping("/publish")
    public ResponseEntity<Map<String, Object>> publishVideo(@RequestBody Map<String, String> request) {
        String appId = request.get("appId");
        String storeId = request.get("storeId");
        String accessToken = request.get("access_token");
        log.info("收到发布视频请求，appId: {}, storeId: {}", appId, storeId);
        
        try {
            if (accessToken == null || accessToken.isEmpty()) {
                Map<String, Object> hint = new HashMap<>();
                hint.put("success", false);
                hint.put("message", "缺少access_token。请先通过授权流程获取，或直接在请求体中传入access_token用于一次性发布");
                hint.put("authorize_url", ksAuthService.buildAuthorizeUrl(appId));
                return ResponseEntity.ok(hint);
            }
            
            if (storeId == null || storeId.isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("success", false);
                errorResult.put("message", "缺少storeId参数");
                return ResponseEntity.ok(errorResult);
            }

            Map<String, Object> result = ksPublishService.publishVideo(accessToken, appId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("发布视频失败", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "发布视频失败: " + e.getMessage());
            return ResponseEntity.ok(errorResult);
        }
    }
}